﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DO.Domain.Repositories;

/*Referirse a Common puesto que no habrá descubrimiento dinámico de servicios*/
using DO.Common.ServiceContracts;
using DO.Common.DTOs;



namespace DO.Domain.Services
{
    public class CustomerService:ICustomerService
    {

        public IRepositoryLocator RepositoryLocator { get; set; }
        public CustomerDTO CreateNewCustomer(CustomerDTO dto)
        {
            var customer = Customer.Create(RepositoryLocator, dto);
            return this.CustomerToCustomerDTO(customer);
        }

        public CustomerDTO GetByIdentity(long identity)
        {
            return this.CustomerToCustomerDTO(this.RepositoryLocator.GetByIdentity<Customer>(identity));
        }

        public CustomerDTO UpdateCustomer(CustomerDTO customerDTO)
        {
            var instance = RepositoryLocator.GetByIdentity<Customer>(customerDTO.Id);
            instance.Update(RepositoryLocator, customerDTO);
            return CustomerToCustomerDTO(instance);
        }

        public CustomerDTOs FindAll()
        {
            var customersFound = this.RepositoryLocator.FindAll<Customer>();
            var resultingList = new CustomerDTOs { CustomersList = new List<CustomerDTO>() };

            //if (customersFound.Count() == 0)
            //{
            //    return resultingList;
            //}
            //else
            //{
            //    customersFound.ToList().ForEach(customer => resultingList.CustomersList.Add(this.CustomerToCustomerDTO(customer)));
            //    return resultingList;
            //}

            if (customersFound.Count() > 0)
            {
                customersFound.ToList().ForEach(customer => resultingList.CustomersList.Add(this.CustomerToCustomerDTO(customer)));     
            }

            return resultingList;
        }

        #region Helper functions
        private CustomerDTO CustomerToCustomerDTO(Customer customer)
        {
            return new CustomerDTO
            {
                Id = customer.Identity,
                Name1 = customer.Name1,
                Name2 = customer.Name2,
                IdIdentification = customer.IdIdentification
            };
        }
        #endregion
    }
}
